package com.gaber.springbootorderrabbitmqproducer.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author gaber
 * @date 2023/9/18 17:54:58
 * @description TODO
 */
@Service
public class OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void makeOrder(String userId, String productId, int num) {
        String orderId = UUID.randomUUID().toString();

        System.out.println("订单生成成功:" + orderId);
        String exchangeName = "fanout_order_exchange";
        String routingKey = "";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
    }

    public void makeDirectOrder(String userId, String productId, int num) {
        String orderId = UUID.randomUUID().toString();

        System.out.println("订单生成成功:" + orderId);
        String exchangeName = "direct_order_exchange";
        String routingKey = "duanxin";
        String routingKey1 = "email";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
        rabbitTemplate.convertAndSend(exchangeName, routingKey1, orderId);
    }

    public void makeTopicOrder(String userId, String productId, int num) {
        String orderId = UUID.randomUUID().toString();

        System.out.println("订单生成成功:" + orderId);
        String exchangeName = "topic_order_exchange";
        String routingKey = "com";
        // #.duanxin.#
        // *.email.#
        // com.#
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
    }

    public void makeTtlOrder(String userId, String productId, int num) {
        String orderId = UUID.randomUUID().toString();

        System.out.println("订单生成成功:" + orderId);
        String exchangeName = "ttl_direct_exchange";
        String routingKey = "ttl";
        // #.duanxin.#
        // *.email.#
        // com.#
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
    }

    public void makeTtlMessageOrder(String userId, String productId, int num) {
        String orderId = UUID.randomUUID().toString();

        System.out.println("订单生成成功:" + orderId);
        String exchangeName = "ttl_direct_exchange";
        String routingKey = "ttlmessage";

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("5000");
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };

        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId, messagePostProcessor);
    }
}
